package com.mf.controller.visibility;

import com.mf.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: lmf
 * @Create: 2025/5/14 21:18
 * @module 可见性
 */

@RestController
@RequestMapping("visibility")
public class Visibility {

    private boolean flag = true;

    @Operation(summary = "有可见性问题的代码--在17中测试不出这个问题了。。。跳过")
    @GetMapping("testVisibility")
    public Result<String> testVisibility() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            while (flag) {
                // ....
            }
            System.out.println("t1线程结束");
        });

        t1.start();
        Thread.sleep(10);
        flag = false;
        System.out.println("主线程将flag改为false");
        return Result.success("当前代码修改了flag但是线程并没有接收到flag变化从而终止线程");
    }


    private volatile boolean flag2 = true;

    @Operation(summary = "volatile解决可见性问题")
    @GetMapping("useVolatile")
    public Result<String> useVolatile() throws InterruptedException {
        new Thread(() -> {
            while (flag2) {
                // 线程正在运行
            }
            System.out.println("线程结束");
        }).start();
        Thread.sleep(50);
        flag2 = false;
        return Result.success("添加volatile后成功结束线程");
    }


}
